package com.ujoku.service.impl;

import com.labillusion.core.database.base.mybatis.dao.BaseDao;
import com.labillusion.core.database.base.mybatis.service.base.impl.BaseServiceImpl;
import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.labillusion.core.platform.web.rest.exception.InvalidRequestException;
import com.labillusion.core.util.StringUtils;
import com.labillusion.core.util.UUIDUtils;
import com.ujoku.context.constants.ExpiredCacheContext;
import com.ujoku.context.constants.MessageConstants;
import com.ujoku.context.constants.StatusConstants;
import com.ujoku.dao.OrderDao;
import com.ujoku.dao.OrderPaymentDao;
import com.ujoku.domain.*;
import com.ujoku.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Andy.Lian on 2014/11/2.
 */
@Service
public class OrderPaymentServiceImpl extends BaseServiceImpl<OrderPayment> implements OrderPaymentService<OrderPayment> {

    @Autowired
    private OrderPaymentDao dao;

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private MyListService myListService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MyListItemService myListItemService;

    @Autowired
    private MessageService messageService;

    @Override
    protected BaseDao<OrderPayment> getBaseDao() {
        return dao;
    }

    @Override
    public OrderPayment buildOrderPayment(Order order, String paymentType, String trade_no){
        if(order.getStatus() > 1){
            throw new InvalidRequestException("order status is invalid.");
        }

        OrderPayment orderPayment = new OrderPayment();
        orderPayment.setId(UUIDUtils.create());
        orderPayment.setOrderId(order.getId());
        Double amount = order.getTotal() - order.getUsedBalanceAmount();

        BigDecimal bg = new BigDecimal(amount).setScale(2, RoundingMode.HALF_UP);
        orderPayment.setAmount(bg.doubleValue());
        orderPayment.setPaymentType(paymentType);
        orderPayment.setDescription("订单支付");
        orderPayment.setMode(trade_no);
        orderPayment.setStatus(StatusConstants.Active);
        if(order.getOrderItemList().size() > 1){
            orderPayment.setGoodsName(order.getOrderItemList().get(0).getGoodsName() + "...等多件");
        }
        else{
            orderPayment.setGoodsName(order.getOrderItemList().get(0).getGoodsName());
        }

        return orderPayment;
    }

    @Override
    public void orderComplete(String trade_no, String paymentType, Order order) {
        Member member = (Member) memberService.selectById(order.getMemberId());
        //更新用户订单数量
        member.setOrderCount(member.getOrderCount() + 1);
        //扣除余额
        if(order.getUsedBalanceAmount() > 0)
            member.setBalance(member.getBalance() - order.getTotal());

        //支付记录
        OrderPayment orderPayment = this.buildOrderPayment(order, paymentType, trade_no);
        super.insert(orderPayment);
        //修改订单状态
        order.setStatus(OrderStatus.Processing);
        orderService.update(order);

        //如果是私人酒窖
        enterMyList(order, member);

        memberService.update(member);
        ExpiredCacheContext.expiredMemberSet.add(member.getUser_id());

        //处理私人酒窖消息
        for(OrderItem orderItem : order.getOrderItemList()) {
            if(!StringUtils.hasText(orderItem.getMyListItemId())){
                continue;
            }

            MyListItem myListItem = (MyListItem) myListItemService.selectById(orderItem.getMyListItemId());
            if(myListItem != null){
                Message message = messageService.bulid(MessageConstants.SOLD, myListItem.getMemberId() , new String[]{myListItem.getGoodsName(), String.valueOf(orderItem.getQty())});
                messageService.insert(message);
            }
        }

    }


    private void enterMyList(Order order, Member member) {
        if(order.getDeliveryType() != DeliveryType.DEPOSIT) {
            return;
        }

        MyList myList = myListService.selectMyListByMemberId(order.getMemberId());
        if(myList == null){
            myList = new MyList();
            myList.setId(UUIDUtils.random());
            myList.setMemberId(order.getMemberId());
            myList.setMemberName(member.getUser_name());
            myList.setMyListItemList(new ArrayList<>());
            myListService.insert(myList);
        }

        for(OrderItem orderItem : order.getOrderItemList()) {
            MyListItem myListItem = myList.getMyListItemList().stream().filter(i -> i.getGoodsId() == orderItem.getGoodsId()).findFirst().orElse(null);
            //新增
            if (myListItem == null){
                myListItem = new MyListItem();
                myListItem.setQty(orderItem.getQty());
                myListItem.setSaleCount(0);
                myListItem.setMyListId(myList.getId());
                myListItem.setId(UUIDUtils.random());
                myListItem.setOnSale(false);
                myListItem.setGoodsId(orderItem.getGoodsId());
                myListItem.setGoodsName(orderItem.getGoodsName());
                myListItem.setInPrice(orderItem.getPrice());
                myListItemService.insert(myListItem);
                myList.getMyListItemList().add(myListItem);
            }
            //更新
            else{
                myListItem.setQty(myListItem.getQty() + orderItem.getQty());
                myListItem.setPrice(orderItem.getPrice());
                myListItemService.update(myListItem);
            }
        }

        member.setCellarCount(myList.getMyListItemList().size());
    }

}
